import logging
import json

from .error_code import code_to_msg

from flask import make_response

logger = logging.getLogger(__name__)


def response(code, msg, data):
    result_text = json.dumps({
        "code": code,
        "msg": msg,
        "data": data
    }, ensure_ascii=False)
    rst = make_response(result_text)
    rst.headers['Access-Control-Allow-Origin'] = '*'
    rst.headers['Access-Control-Allow-Method'] = '*'
    rst.headers['Access-Control-Allow-Credentials'] = 'true'
    rst.headers['Access-Control-Allow-Header'] = '*'
    return rst


class APIException(Exception):
    code = 200
    msg = "System Error"
    data = {}

    def __init__(self, code, data={}):
        Exception.__init__(self)
        self.code = code
        self.msg = code_to_msg[self.code]
        self.data = data

    def to_dict(self):
        logger.warning(msg=self.msg)

        return response(400, self.msg, self.data)
